package com.gking.centerSystem.service.RolePermissions;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gking.centerSystem.common.ProgramException;
import com.gking.centerSystem.common.Result;
import com.gking.centerSystem.entity.dto.RolePermissionListDto;
import com.gking.centerSystem.entity.Permissions;
import com.gking.centerSystem.entity.RolePermissions;
import com.gking.centerSystem.entity.enums.UserDataSetTypeEnum;
import com.gking.centerSystem.mapper.RolePermissionsMapper;
import com.gking.centerSystem.service.Permissions.PermissionsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service
public class RolePermissionsServiceImpl extends ServiceImpl<RolePermissionsMapper, RolePermissions> implements RolePermissionsService {

    @Resource
    private PermissionsService permissionsService;

    @Resource
    private RolePermissionsMapper rolePermissionsMapper;

    /**
     * 获取角色权限详情
     *
     * @param roleId 角色id
     * @return s
     */
    @Override
    public Result<RolePermissionListDto> getRolePermissionsDetail(String roleId) {

        if (roleId.isEmpty()) return Result.error("请将参数补充完整");

        try {
            LambdaQueryWrapper<RolePermissions> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(RolePermissions::getRoleId, roleId);
            List<RolePermissions> list = this.list(wrapper);

            List<String> permissionInfoList = new ArrayList<>();
            List<String> permissionIdList = new ArrayList<>();
            List<Permissions> permissionList = new ArrayList<>();
            for (RolePermissions rolePermissions : list) {
                Permissions permissions = permissionsService.getById(rolePermissions.getPermissionId());
                permissionInfoList.add(permissions.getCode());
                permissionIdList.add(permissions.getId());
                permissionList.add(permissions);
            }

            RolePermissionListDto rolePermissionListDto = new RolePermissionListDto();
            rolePermissionListDto.setPermissionIdList(permissionIdList);
            rolePermissionListDto.setPermissionInfoList(permissionInfoList);
            rolePermissionListDto.setPermissionsList(permissionList);

            return Result.success("获取角色权限列表成功！", rolePermissionListDto);
        } catch (Exception e) {
            log.error("获取角色权限列表失败！ {} ", e.getMessage());
            throw new ProgramException();
        }
    }

    @Override
    public Result<RolePermissionListDto> getRolePermissionsDetail(List<String> roleIds) {
        try {
            RolePermissionListDto rolePermissionListDto = new RolePermissionListDto();
            if (roleIds == null || roleIds.isEmpty()) return Result.success("为空！", rolePermissionListDto);

            LambdaQueryWrapper<RolePermissions> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(RolePermissions::getRoleId, roleIds);
            List<RolePermissions> list = this.list(wrapper);

            List<String> permIds = list.stream()
                    .map(RolePermissions::getPermissionId)
                    .collect(Collectors.toList());
            if (permIds.isEmpty()) return Result.success("为空！", rolePermissionListDto);
            List<Permissions> permissionsByIds = rolePermissionsMapper.getPermissionsByIds(permIds);


            List<String> permissionInfoList = new ArrayList<>();
            List<String> permissionIdList = new ArrayList<>();
            List<Permissions> permissionList = new ArrayList<>();
            for (Permissions permissions : permissionsByIds) {
                permissionInfoList.add(permissions.getCode());
                permissionIdList.add(permissions.getId());
                permissionList.add(permissions);
            }
            rolePermissionListDto.setPermissionIdList(permissionIdList);
            rolePermissionListDto.setPermissionInfoList(permissionInfoList);
            rolePermissionListDto.setPermissionsList(permissionList);

            return Result.success("获取角色权限列表成功！", rolePermissionListDto);
        } catch (Exception e) {
            log.error("获取角色权限列表失败！ {} ", e.getMessage());
            throw new ProgramException();
        }
    }

    /**
     * 为角色设置权限
     *
     * @param roleId            角色id
     * @param type              类型 （refresh, add, remove）
     * @param permissionsIdList 权限id 列表
     * @return s
     */
    @Transactional
    @Override
    public Result<String> setRolePermissions(String roleId, String type, List<String> permissionsIdList) {

        if (roleId.isEmpty() || permissionsIdList.isEmpty() || type.isEmpty())
            return Result.error("请将参数补充完整");
        if (UserDataSetTypeEnum.getEnumByValue(type) == null) return Result.error("type参数错误");


        try {
            // 删除角色权限
            if (Objects.equals(type, UserDataSetTypeEnum.REMOVE.getValue())) {
                LambdaQueryWrapper<RolePermissions> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(RolePermissions::getRoleId, roleId);
                wrapper.in(RolePermissions::getPermissionId, permissionsIdList);

                this.remove(wrapper);
                return Result.success("删除角色权限成功");
            }

            List<RolePermissions> rolePermissionsList = new ArrayList<>();
            for (String permissionId : permissionsIdList) {
                RolePermissions rolePermissions = new RolePermissions();
                rolePermissions.setRoleId(roleId);
                rolePermissions.setPermissionId(permissionId);
                rolePermissionsList.add(rolePermissions);
            }

            //重新为角色设置权限，全部重新设置
            if (Objects.equals(type, UserDataSetTypeEnum.REFRESH.getValue())) {
                LambdaQueryWrapper<RolePermissions> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(RolePermissions::getRoleId, roleId);

                this.remove(wrapper);
                this.saveBatch(rolePermissionsList);
                return Result.success("设置角色权限成功");
            }

            //为角色在已有基础上添加权限
            if (Objects.equals(type, UserDataSetTypeEnum.ADD.getValue())) {
                LambdaQueryWrapper<RolePermissions> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(RolePermissions::getRoleId, roleId);
                wrapper.in(RolePermissions::getPermissionId, permissionsIdList);
                if (this.count(wrapper) > 0) return Result.error("角色权限已存在");

                this.saveBatch(rolePermissionsList);
                return Result.success("设置角色权限成功");
            }

            return Result.error("设置角色权限失败");
        } catch (Exception e) {
            log.error("设置角色权限失败！ {} ", e.getMessage());
            throw new ProgramException();
        }
    }
}
